# Create your views here.
from backend.models import *
from django.http import HttpResponse, Http404
from django.template import Context
from django.template.loader import get_template
from django.contrib.auth.models import User
from django.template import RequestContext
from django.template import TemplateDoesNotExist
from django.views.defaults import page_not_found
import MySQLdb
import math
from django.contrib.auth import logout
import bookstore.settings
rootPath = bookstore.settings.ROOT_PATH
from django.http import HttpResponseRedirect
from django.contrib.auth import logout
import cgi

var_back_category = ''
var_category_paging = ''
var_book = ''
var_book_paging = ''
var_book_category = ''
var_check = ''
var_user = ''
var_user_paging = ''
loged = ''
bookNameData = ''
catNameData = ''
var_book_head = ''
var_static = ''
var_detail_static = ''
var_title_static = ''
var_detail_setting = ''
var_title_setting = ''
var_integer = 0
var_setting = ''
var_step2 = ''
total_book = 0
total_user = 0
total_like = 0
total_sold = 0
list_category = ''

var_user_edit = ''
var_password_edit = ''
var_email_edit = ''
var_company_edit = ''
var_phone_edit = ''
var_address_edit = ''

var_category_edit = ''
var_weight_edit = ''
var_status_edit = ''

var_title_edit = ''
var_bweight_edit = ''
var_summary_edit = ''
var_detail_edit = ''
var_bcategory_edit = ''

user_head =''
user_end=''
static_end =''
setting_end=''

admin_addcategory=''
admin_addbook=''
admin_category_op=''
admin_book_op=''
admin_book_cat_op =''
def backend_page(request):
	if check_loged(request) == False:
		str = '%s/login' % (rootPath)
		return HttpResponseRedirect(str)
	if isAdmin(request)==0:
		template = get_template('backend/index.html')
	else:	
		template = get_template('backend/index.html')
	return return_request(template, request)

def book_page(request):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    template = get_template('backend/vBookModule.html')
    variables = Context({ 'rootPath': rootPath })
    output = template.render(variables)
    return HttpResponse(output)

def view_category(request,page):
    global var_back_category
    global var_category_paging
    var_back_category = ''
    var_category_paging = ''
    rows = getAllCategory()
    len = 0
    for row in rows:
        len += 1
    numberofpage = int(math.ceil(len / 5.0))
    j = -1
    for i in range ((page - 1) * 5, page * 5):
        j += 1
        if i >= len:
            break
        row = rows[i]
        option =''
        link1 = rootPath + "/backend/category/edit/%s" % (row[0])
        link2 = rootPath + "/backend/category/delete/%s/%s" % (row[0], page)		
        if isAdmin(request):
            option ='<td class="options-width">\n\
                    <a href="%s "title="Edit" class="icon-1 info-tooltip"></a>\n\
                    <a href="%s"title="Delete" class="icon-22 info-tooltip"></a>\n\
                    </td>\n\
					'	%(link1, link2)
        if j % 2 == 1:
            var_back_category += '<tr class="alternate-row">\n\
                        '
        else:
            var_back_category += '<tr class="">\n\
                        '
        linkbook = rootPath + '/backend/book/view/category/%i' % (row[0])
        var_back_category += '\n\
                    <td>%s</td>\n\
                    <td>%s</td>\n\
                    <td><a href="%s">View Books</a></td>\n\
					%s\
                </tr>\n\
                ' % (row[0], row[1], linkbook,option)
    previous = 1
    next = 1
    if (page == 1):
        previous = 1
    else:
        previous = page - 1
    if(page == numberofpage):
        next = page
    else:
        next = page + 1
    link = rootPath + '/backend/category/view/page01'
    link1 = rootPath + '/backend/category/view/page0%s' % (previous)
    link2 = rootPath + '/backend/category/view/page0%s' % (next)
    link3 = rootPath + '/backend/category/view/page0%s' % (numberofpage)
    var_category_paging = '<a href="%s" class="page-far-left"></a>\n\
                <a href="%s" class="page-left"></a>\n\
                <div id="page-info">Page <strong>%s</strong> / 4</div>\n\
                <a href="%s" class="page-right"></a>\n\
                <a href="%s" class="page-far-right"></a>\n\
                ' % (link, link1, page, link2, link3)
                
def back_category_page(request):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    return HttpResponseRedirect('page01')

def category_delete(request, cid, page):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    deleteCategory(cid)
    str = rootPath + '/backend/category/view/page%s' % (page)
    return HttpResponseRedirect(str)
def category_edit_page(request, cid):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    global var_category_edit
    global var_weight_edit
    global var_status_edit
    row = getCategoryByID(cid)
    var_category_edit = row[1]
    var_weight_edit = row[2]
    var_status_edit = row[3]
    if request.method == "POST":
        var_category_edit = request.POST['name']
        var_weight_edit = request.POST['weight']
        var_status_edit = request.POST['status']
        updateCategory(cid, var_category_edit, var_weight_edit, var_status_edit)
        str = rootPath + '/backend/category/view'
        return HttpResponseRedirect(str)
    template = get_template('backend/editcategory.html')
    return return_request(template, request)
    
    
def back_category_page_paging(request, page):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    currentpage = int(page)
    view_category(request,currentpage)
    template = get_template('backend/category.html')
    return return_request(template, request)

def view_book(request,page):
    global var_book
    global var_book_paging
    global var_book_head
    var_book = ''
    var_book_paging = ''
    rows = getAllBook()
    len = 0
    for row in rows:
        len += 1
    numberofpage = int(math.ceil(len / 5.0))
    option =''
    if isAdmin(request):
        option = '<th class="table-header-options line-left"><span\n\
                            class="none-link">Options</span>\n\
                        </th>\n\
						'	
    var_book_head = '<tr>\n\
                        <th class="table-header-check table-header-repeat"><a href="">ID</a>\n\
                        </th>\n\
                        <th class="table-header-repeat line-left minwidth-1"><a\n\
                            href="">Name</a></th>\n\
                        <th class="table-header-repeat line-left"><a href="">Category</a>\n\
                        </th>\n\
                        <th class="table-header-repeat line-left"><a href="">Created</a>\n\
                        </th>\n\
						%s\
                    </tr>\n\
                    ' % (option)
    j = -1                
    for i in range ((page - 1) * 5, page * 5):
        j += 1           
        if i >= len:
            break
        row = rows[i]
        linkedit = rootPath + "/backend/book/edit/%s" %(row[0])
        linkdelete = rootPath + "/backend/book/delete/%s/%s" % (row[0], page)
        linkspecial = rootPath + "/backend/book/special/%s/%s" % (row[0], page)
        linkfeature = rootPath + "/backend/book/feature/%s/%s" % (row[0], page)
        if(row[4] == 1):
            var_feature = "icon-52 info-tooltip"
        else: 
            var_feature = "icon-5 info-tooltip"
        if(row[5] == 1):
            var_special = "icon-32 info-tooltip"
        else: 
            var_special = "icon-3 info-tooltip"
        
        if j % 2 == 1:
            var_book += '<tr class="alternate-row">\n\
                        '
        else:
            var_book += '<tr class="">\n\
                    '
        option =''
        if isAdmin(request):
            option ='<td class="options-width"><a\n\
                            href="%s" title="Edit"\n\
                            class="icon-1 info-tooltip"></a> <a\n\
                            href="%s"\n\
                            title="Delete" class="icon-2 info-tooltip"></a> <a\n\
                            href="%s"\n\
                            title="Special" class="%s"></a> <a\n\
                            href="%s"\n\
                            title="Feature" class="%s"></a></td>\n\
							' %(linkedit, linkdelete, linkspecial, var_special, linkfeature, var_feature)
        var_book += '\n\
                        <td>%s</td>\n\
                        <td>%s</td>\n\
                        <td>%s</td>\n\
                        <td>%s</td>\n\
                        %s\
                    </tr>' % (row[0], row[1], row[3], row[2],option)
    previous = 1
    next = 1
    if (page == 1):
        previous = 1
    else:
        previous = page - 1
    if(page == numberofpage):
        next = page
    else:
        next = page + 1
    link = rootPath + '/backend/book/view/page01'
    link1 = rootPath + '/backend/book/view/page0%s' % (previous)
    link2 = rootPath + '/backend/book/view/page0%s' % (next)
    link3 = rootPath + '/backend/book/view/page0%s' % (numberofpage)
    var_book_paging = '<a href="%s"\n\
                        class="page-far-left"></a>\n\
                        <a href="%s"\n\
                        class="page-left"></a>\n\
                        <div id="page-info">\n\
                            Page <strong>%s</strong> / 11\n\
                        </div> <a href="%s"\n\
                        class="page-right"></a> <a\n\
                        href="%s"\n\
                        class="page-far-right"></a></td>\n\
                ' % (link, link1, page, link2, link3)
def book_edit_page(request, nid):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    global var_title_edit
    global var_bweight_edit 
    global var_summary_edit 
    global var_detail_edit
    global var_bcategory_edit
    #var_bcategory_edit =''
    cates = getAllCategory()
    row = getBookEditByID(nid)
    var_title_edit = row[0]
    var_bweight_edit = row[1]
    var_summary_edit = row[2]
    var_detail_edit = row[3]
    chosedCategory = row[4]
    var_bcategory_edit = '<option value="%s"> %s</option>' %(chosedCategory,chosedCategory)
    for c in cates:
            if c[1] != 	chosedCategory:
                var_bcategory_edit += '<option value="%s"> %s</option>' % (c[1], c[1])
	
    if request.method == "POST":
        var_title_edit = request.POST['title']
        var_bweight_edit = request.POST['weight']
        var_summary_edit = request.POST['summary']
        var_detail_edit = request.POST['detail']
        var_bcategory_edit = request.POST['category']
        editBook(nid, var_title_edit, var_bweight_edit, var_summary_edit, var_detail_edit, var_bcategory_edit)
        str = rootPath + '/backend/book/view'
        return HttpResponseRedirect(str)
    template = get_template('backend/booksetting.html')
    return return_request(template, request)    
def book_delete(request, nid, page):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    deleteBook(nid)
    str = rootPath + '/backend/book/view/page%s' % (page)
    return HttpResponseRedirect(str)
    
def set_special_book(request, nid, page):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    setSpecialBook(nid)
    str = rootPath + '/backend/book/view/page%s' % (page)
    return HttpResponseRedirect(str)
    
def set_feature_book(request, nid, page):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    setFeatureBook(nid)
    str = rootPath + '/backend/book/view/page%s' % (page)
    return HttpResponseRedirect(str)
    
def view_book_filter(bName, cName):
    global var_book
    global var_book_head
    global var_book_paging
    var_book = ''
    var_book_head = ''
    var_book_paging = ''
    rows = ()
    if(bName == '' and cName == ''):
        rows = getAllBook()
    elif (cName == ''):
        rows = getBookFromName(bName)
    elif (bName == ''):
        rows = getBookFromCategory(cName)
    else:
        rows = getBookFromName(bName)
        rows += getBookFromCategory(cName)
    
    var_book_head = '<tr>\n\
                        <th class="table-header-check table-header-repeat"><a href="">ID</a>\n\
                        </th>\n\
                        <th class="table-header-repeat line-left minwidth-1"><a\n\
                            href="">Name</a></th>\n\
                        <th class="table-header-repeat line-left"><a href="">Category</a>\n\
                        </th>\n\
                        <th class="table-header-repeat line-left"><a href="">Created</a>\n\
                        </th>\n\
                        <th class="table-header-options line-left"><span\n\
                            class="none-link">Options</span>\n\
                        </th>\n\
                    </tr>\n\
                    '
    for row in rows:
        if(row[4] == 1):
            var_feature = "icon-52 info-tooltip"
        else: 
            var_feature = "icon-5 info-tooltip"
        if(row[5] == 1):
            var_special = "icon-32 info-tooltip"
        else: 
            var_special = "icon-3 info-tooltip"
        linkedit = rootPath + "/backend/book/edit/%s" %(row[0])
        linkdelete = rootPath + "/backend/book/delete/%s" % (row[0])
        linkspecial = rootPath + "/backend/book/special/%s" % (row[0])
        linkfeature = rootPath + "/backend/book/feature/%s" % (row[0])
        var_book += '<tr class="">\n\
                        <td>%s</td>\n\
                        <td>%s</td>\n\
                        <td>%s</td>\n\
                        <td>%s</td>\n\
                        <td class="options-width"><a\n\
                            href="%s" title="Edit"\n\
                            class="icon-1 info-tooltip"></a> <a\n\
                            href="%s"\n\
                            title="Delete" class="icon-2 info-tooltip"></a> <a\n\
                            href="%s"\n\
                            title="Special" class="%s"></a> <a\n\
                            href="%s"\n\
                            title="Feature" class="%s"></a></td>\n\
                    </tr>' % (row[0], row[1], row[3], row[2],linkedit, linkdelete, linkspecial, var_special, linkfeature, var_feature)
def book_delete3(request, nid):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    deleteBook(nid)
    str = rootPath + '/backend/book/view'
    return HttpResponseRedirect(str)    
def set_special_book3(request, nid):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    setSpecialBook(nid)
    str = rootPath + '/backend/book/view'
    return HttpResponseRedirect(str)
    
def set_feature_book3(request, nid):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    setFeatureBook(nid)
    str = rootPath + '/backend/book/view' 
    return HttpResponseRedirect(str)        
    
def back_book_page(request):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
        
    if request.method == "POST":
        viewFilter()
        bName = request.POST['bname']
        cName = request.POST['category']
        view_book_filter(bName, cName)
        template = get_template('backend/bookpage.html')
        return return_request(template, request)
    else:
        return HttpResponseRedirect('page01')

def back_book_page_paging(request, page):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    viewFilter()
    currentpage = int(page)
    view_book(request,currentpage)
    template = get_template('backend/bookpage.html')
    return return_request(template, request)

def view_user(request,page):
    global var_user
    global var_user_paging
    var_user = ''
    var_user_paging = ''
    rows = getAllUser()
    len = 0
    for row in rows:
        len += 1
    numberofpage = int(math.ceil(len / 5.0))
    j = -1
    for i in range ((page - 1) * 5, page * 5):
        j += 1
        if i >= len:
            break
        row = rows[i]
        link1 = rootPath + "/backend/user/edit/%s" % (row[0])
        link2='' 
        if (row[8] == 1):
            isadmin = 'Admin'
        else:
            isadmin = 'Normal'
            link2='<a href="%s/backend/user/delete/%s/%s" class="icon-10 info-tooltip"></a>' % (rootPath,row[0], page)
        if j % 2 == 1:
            var_user += '<tr class="alternate-row">\n\
                        '
        else:
            var_user += '<tr class="">\n\
                 '
        var_user += '\n\
                        <td>%s</td>\n\
                        <td>%s</td>\n\
                        <td><a href="mailto:%s">%s</a></td>\n\
                        <td>%s</td>\n\
                        <td class="options-width"><a href="%s"\n\
                            class="icon-1 info-tooltip"></a>\n\
                            %s</td>\n\
                    </tr>' % (row[0], row[1], row[4], row[4], isadmin, link1, link2)
    previous = 1
    next = 1
    if (page == 1):
        previous = 1
    else:
        previous = page - 1
    if(page == numberofpage):
        next = page
    else:
        next = page + 1
    link = rootPath + '/backend/user/view/page01'
    link1 = rootPath + '/backend/user/view/page0%s' % (previous)
    link2 = rootPath + '/backend/user/view/page0%s' % (next)
    link3 = rootPath + '/backend/user/view/page0%s' % (numberofpage)
    var_user_paging = '<a href="%s" class="page-far-left"></a> <a\n\
                    href="%s" class="page-left"></a>\n\
                    <div id="page-info">\n\
                        Page <strong><span id="page">%s</span> </strong> / <span\n\
                            id="numPages">%s</span>\n\
                    </div> <a href="%s" class="page-right"></a> <a\n\
                    href="%s" class="page-far-right"> </a>\n\
                ' % (link, link1, page, numberofpage, link2, link3)
                
def user_page(request):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    if isAdmin(request) ==0 :
        return HttpResponseRedirect(rootPath+'/backend')
    return HttpResponseRedirect('page01')

def user_page_paging(request, page):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    currentpage = int(page)
    if isAdmin(request) ==0 :
        return HttpResponseRedirect(rootPath+'/backend')
    view_user(request,currentpage)
    template = get_template('backend/userpage.html')
    return return_request(template, request)
    
def user_delete(request, id, page):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    if isAdmin(request) ==0 :
        return HttpResponseRedirect(rootPath+'/backend')
    deleteUser(id)
    str = rootPath + '/backend/user/view/page%s' % (page)
    return HttpResponseRedirect(str)    
def user_edit_page(request, id):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    if isAdmin(request) ==0 :
        return HttpResponseRedirect(rootPath+'/backend')
    global var_user_edit
    global var_password_edit
    global var_email_edit
    global var_phone_edit
    global var_company_edit
    global var_address_edit
    row = getUserByID(id)

    var_user_edit = row[1]
    var_password_edit = row[5]
    var_email_edit = row[4]
   
    row1 = getUserInfoByID(id)
    var_company_edit = row1[2]
    var_phone_edit = row1[1]
    var_address_edit = row1[3]
    if request.method == "POST":
        var_user_edit = request.POST['username']
        var_password_edit = request.POST['password']
        var_email_edit = request.POST['email']
        var_company_edit = request.POST['company']
        var_phone_edit = request.POST['phone']
        var_address_edit = request.POST['address']
        updateUser(id, var_password_edit, var_email_edit, var_company_edit, var_phone_edit, var_address_edit)
        str = rootPath + '/backend/user/view'
        return HttpResponseRedirect(str)
    template = get_template('backend/usersetting.html')
    return return_request(template, request)
    
def view_static():
    global var_static
    var_static = ''
    rows = getAllStatic()
    j = -1
    for row in rows:        
        j += 1
        if j % 2 == 1:
            var_static += '<tr class="alternate-row">\n\
                        '
        else:
            var_static += '<tr class="">\n\
                    '
        var_static += '\n\
                    <td>%s</td>\n\
                    <td>%s</td>\n\
                    <td>%s</td>\n\
                    <td class="options-width">\n\
                        <a href="%s/backend/static/edit/%s" title="Edit"    class="icon-1 info-tooltip"></a>\n\
                    </tr>' % (row[0], row[1], row[2], rootPath, row[0])
    
def view_setting():
    global var_setting
    var_setting = ''
    rows = getAllSetting()
    j = -1
    for row in rows:
        j += 1
        if j % 2 == 1:
            var_setting += '<tr class="alternate-row">\n\
                        '
        else:
            var_setting += '<tr class="">\n\
                    '
        var_setting += '\n\
                    <td>%s</td>\n\
                    <td>%s</td>\n\
                    <td>%s</td>\n\
                    <td class="options-width">\n\
                        <a href="%s/backend/setting/edit/%s" title="Edit"    class="icon-1 info-tooltip"></a>\n\
                    </tr>' % (row[0], row[1], row[2], rootPath, row[0])
    
def detail_category(request,cid):
    global var_book_category
    var_book_category = ''        
    rows = getBookOfCategory(cid)
    len = 0
    for row in rows:
        if(row[4] == 1):
            var_feature = "icon-52 info-tooltip"
        else: 
            var_feature = "icon-5 info-tooltip"
        if(row[5] == 1):
            var_special = "icon-32 info-tooltip"
        else: 
            var_special = "icon-3 info-tooltip"
        linkedit = rootPath + "/backend/book/edit/%s" %(row[0])
        linkdelete = rootPath + "/backend/book/view/category/delete/%s/%s" % (row[0], cid)
        linkspecial = rootPath + "/backend/book/view/category/special/%s/%s" % (row[0], cid)
        linkfeature = rootPath + "/backend/book/view/category/feature/%s/%s" % (row[0], cid)
        option =''
        if isAdmin(request):
            option ='<td class="options-width"><a\n\
                            href="%s" title="Edit"\n\
                            class="icon-1 info-tooltip"></a> <a\n\
                            href="%s"\n\
                            title="Delete" class="icon-2 info-tooltip"></a> <a\n\
                            href="%s"\n\
                            title="Special" class="%s"></a> <a\n\
                            href="%s"\n\
                            title="Feature" class="%s"></a></td>\n\
							' %(linkedit, linkdelete, linkspecial, var_special, linkfeature, var_feature)
        var_book_category += '<tr class="">\n\
                        <td>%s</td>\n\
                        <td>%s</td>\n\
                        <td>%s</td>\n\
                        <td>%s</td>\n\
                        %s\
                    </tr>' % (row[0], row[1], row[3], row[2],option)  

def book_delete2(request, nid, page):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    deleteBook(nid)
    str = rootPath + '/backend/book/view/category/%s' % (page)
    return HttpResponseRedirect(str)
def set_special_book2(request, nid, page):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    setSpecialBook(nid)
    str = rootPath + '/backend/book/view/category/%s' % (page)
    return HttpResponseRedirect(str)
    
def set_feature_book2(request, nid, page):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    setFeatureBook(nid)
    str = rootPath + '/backend/book/view/category/%s' % (page)
    return HttpResponseRedirect(str)    
    
def view_category_book(request, cid):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    detail_category(request,cid)
    template = get_template('backend/bookofcategory.html')
    return return_request(template, request)
    
def add_category_page(request):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    if isAdmin(request) ==0 :
        return HttpResponseRedirect(rootPath+'/backend')
    global var_check
    OldCategory = getAllCategory()
    if request.method == "POST":
        name = request.POST['name']
        weight = request.POST['weight']
        status = request.POST['status']
        kt = 0
        id = 0
        for i in OldCategory:
            if (i[1] == name): 
                kt = 0            
                break
            else:
                kt = 1
        if(kt == 1):
            addNewCategory(name, weight, status)        
            template = get_template('backend/addcategory.html')
            var_check = "<B><I>Insert Successfull !</I></B>"
            return return_request(template, request)
        else:
            var_check = "<B><I>Category Name already exists ! Choose another Name !</I></B>"            
    template = get_template('backend/addcategory.html')
    return return_request(template, request)

def check_loged(request):
	global user_head
	global user_end
	global loged
	global static_end
	global setting_end
	global admin_addbook
	global admin_addcategory
	global admin_category_op
	global admin_book_op
	global admin_book_cat_op
	user_head=''
	user_end=''
	static_end =''
	setting_end=''
	admin_addbook=''
	admin_addcategory =''
	admin_category_op=''
	admin_book_op=''
	admin_book_cat_op =''
	if isAdmin(request):
		user_head ='<div class="nav-divider">&nbsp;</div>\n\
        <ul\
		'
		user_end = 'class="select"><li><a href="%s/backend/user/view/"><b>Users</b><!--[if IE 7]><!--></a><!--<![endif]-->\n\
		<!--[if lte IE 6]><table><tr><td><![endif]-->\n\
		<div class="select_sub show">\n\
			<ul class="sub">\n\
				<li><a href="%s/backend/user/view/">View all users</a></li>\n\
			</ul>\n\
		</div>\n\
		<!--[if lte IE 6]></td></tr></table></a><![endif]-->\n\
		</li>\n\
		</ul>\n\
		' %(rootPath,rootPath)
		static_end='class="select"><li><a href="%s/backend/static/view"><b>Static</b><!--[if IE 7]><!--></a><!--<![endif]-->\n\
		<!--[if lte IE 6]><table><tr><td><![endif]-->\n\
		<div class="select_sub show">\n\
			<ul class="sub">\n\
				<li><a href="%s/backend/static/view/">View all statics</a></li>\n\
			</ul>\n\
		</div>\n\
		<!--[if lte IE 6]></td></tr></table></a><![endif]-->\n\
		</li>\n\
		</ul>\n\
		' %(rootPath,rootPath)
		setting_end=' class="select">\n\
		<li><a href="%s/backend/setting/view/"><b>Settings</b><!--[if IE 7]><!--></a><!--<![endif]-->\n\
		<!--[if lte IE 6]><table><tr><td><![endif]-->\n\
		<div class="select_sub">\n\
			<ul class="sub">\n\
				<li><a href="%s/backend/setting/view/">View all settings</a></li>\n\
			</ul>\n\
		</div>\n\
		<!--[if lte IE 6]></td></tr></table></a><![endif]-->\n\
		</li>\n\
		</ul>\n\
		' %(rootPath,rootPath)
		admin_addbook='<li><a href="%s/backend/book/add/">Add book</a></li>' %(rootPath)
		admin_addcategory='<li><a href="%s/backend/category/add/new">Add category</a></li>' %(rootPath)
		admin_category_op='<th class="table-header-options line-left"><span class="none-link">Options</span></th>'
		admin_book_cat_op ='<th class="table-header-options line-left"><span\n\
							class="none-link">Options</span>\n\
						</th>\n\
						'
	user = request.user
	name = user.username
	if(name == ''):
		return False
	loged = name
	return True

def isAdmin(request):
	user = request.user
	return user.is_superuser
	
def viewFilter ():
    global bookNameData
    global catNameData
    bookNameData = ''
    catNameData = ''
    bookNameData = getBookName()
    catNameData = getCatName()

def static_page(request):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    if isAdmin(request) ==0 :
        return HttpResponseRedirect(rootPath+'/backend')
    view_static()
    template = get_template('backend/staticpage.html')
    return return_request(template, request)
    
def static_edit_page(request, id):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    if isAdmin(request) ==0 :
        return HttpResponseRedirect(rootPath+'/backend')
    global var_integer
    global var_title_static 
    global var_detail_static
    if request.method == "POST":
        var_integer = id
        detail = request.POST['detail']
        submitEditStatic(id, detail)
        str = '%s/backend/static/view/' % (rootPath)
        return HttpResponseRedirect(str)
    else:    
        row = getDetailStatic(id)
        var_title_static = row[1]
        var_detail_static = row[0]
        template = get_template('backend/staticeditpage.html')
        return return_request(template, request)
    
def setting_page(request):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    if isAdmin(request) ==0 :
        return HttpResponseRedirect(rootPath+'/backend')
    view_setting()
    template = get_template('backend/settingpage.html')
    return return_request(template, request)
    
def setting_edit_page(request, id):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    if isAdmin(request) ==0 :
        return HttpResponseRedirect(rootPath+'/backend')
    global var_title_setting 
    global var_detail_setting
    if request.method == "POST":
        detail = request.POST['detail']
        submitEditSetting(id, detail)
        str = '%s/backend/setting/view/' % (rootPath)
        return HttpResponseRedirect(str)
    else:    
        row = getDetailSetting(id)
        var_title_setting = row[0]
        var_detail_setting = row[1]
        template = get_template('backend/settingeditpage.html')
        return return_request(template, request)    
        
def book_add_page(request):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    if isAdmin(request) ==0 :
        return HttpResponseRedirect(rootPath+'/backend')
    global list_category
    list_category = ''
    rows = getAllCategory()
    for row in rows:
        list_category += '<option value="%s">%s</option>' % (row[1], row[1])
    form_data = cgi.FieldStorage()
    if request.method == "POST":
        title = request.POST['title']
        weight = request.POST['weight']
        summary = request.POST['summary']
        detail = request.POST['detail']
        category = request.POST['category']
        thumbnail = 'C:\Users\Public\Pictures\Sample Pictures\Desert.jpg'
        addABook(title, weight, summary, detail, category, thumbnail)
        str = rootPath + '/backend/book/add/step2'
        return HttpResponseRedirect(str)
    template = get_template('backend/addbook.html')
    return return_request(template, request)
    
def book_add_step2_page(request):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    if isAdmin(request) ==0 :
        return HttpResponseRedirect(rootPath+'/backend')
    if request.method == "POST":
        arrayCheck = ()
        if request.POST.has_key('isRelated[]'):
            arrayCheck = request.POST.getlist('isRelated[]')
        if(arrayCheck):
            for each in arrayCheck:
                addRelatedBook(each)
        str = rootPath + '/backend/book/view/'
        return HttpResponseRedirect(str)
    view_step2()
    template = get_template('backend/addbookstep2.html')
    return return_request(template, request)
    
    
def view_step2():
    global var_step2
    var_step2 = ''
    rows = getAllBook()
    i = 0
    for row in rows:
        nid = row[0]
        title = row[1]
        category = row[3]
        created = row[2]
        if i % 2 == 1:
            var_step2 += '<tr class="alternate-row">'
        else:
            var_step2 += '<tr class="">'
        var_step2 += '\n\
                        <td><input  type="checkbox" value="%s" name="isRelated[]"  /></td>\n\
                        <td>%s</td>\n\
                        <td>%s</td>\n\
                        <td>%s</td>\n\
                        <td>%s</td>\n\
                </tr>\n\
                ' % (nid, nid, title, category, created)
        i += 1

def dashboard_page(request):
    if check_loged(request) == False:
        str = '%s/login' % (rootPath)
        return HttpResponseRedirect(str)
    global total_book
    global total_user
    global total_like
    global total_sold
    total_book = getNumBook()
    total_user = getNumUser()
    total_like = getNumLike()
    total_sold = getNumSold()
    template = get_template('backend/dashboardpage.html')
    return return_request(template, request)
	
	
def return_request(template, request):
    variables = RequestContext(request, {'rootPath':rootPath, 'var_back_category':var_back_category, 'var_category_paging':var_category_paging, 'var_book':var_book, 'var_book_paging':var_book_paging, 'var_book_category':var_book_category, 'var_check':var_check, 'var_user':var_user, 'var_user_paging':var_user_paging, 'loged':loged, 'bookNameData':bookNameData, 'catNameData':catNameData
    , 'var_book_head':var_book_head, 'var_static':var_static, 'var_detail_static':var_detail_static, 'var_title_static':var_title_static
    , 'var_integer':var_integer, 'var_setting':var_setting, 'var_detail_setting':var_detail_setting, 'var_title_setting':var_title_setting
    , 'var_step2':var_step2, 'total_book':total_book, 'total_user':total_user, 'total_like':total_like, 'total_sold':total_sold, 'list_category':list_category, 'var_user_edit':var_user_edit
    , 'var_password_edit':var_password_edit, 'var_email_edit':var_email_edit, 'var_company_edit':var_company_edit, 'var_phone_edit':var_phone_edit, 'var_address_edit':var_address_edit
    , 'var_category_edit':var_category_edit, 'var_weight_edit':var_weight_edit, 'var_status_edit':var_status_edit
    , 'var_title_edit':var_title_edit, 'var_bweight_edit':var_bweight_edit, 'var_summary_edit':var_summary_edit, 'var_detail_edit':var_detail_edit, 'var_bcategory_edit':var_bcategory_edit
	, 'user_end':user_end,'user_head':user_head,'static_end':static_end,'setting_end':setting_end,'admin_addcategory':admin_addcategory
	, 'admin_addbook':admin_addbook,'admin_category_op':admin_category_op,'admin_book_op':admin_book_op,'admin_book_cat_op':admin_book_cat_op})
    output = template.render(variables)
    return HttpResponse(output)
	
